<template>
  <div ref="container" class="live-container shadow-font" @click.right="handleClick">
    <template v-for="item in currentList" :key="item.key">
      <WelcomeChat v-if="item.cmd === 'WELCOME'" :data="item"/>
      <RoomChat v-else-if="item.cmd === 'MSG'" :data="item"/>
      <SuperChat v-else-if="item.cmd === 'SC'" :data="item"/>
      <VipChat v-else-if="item.cmd === 'VIP'" :data="item"/>
    </template>
  </div>
</template>

<script setup>
import {inject, nextTick, onActivated, provide, readonly, ref, watch} from 'vue'
import WelcomeChat from '@/components/welcome-chat'
import RoomChat from '@/components/room-chat'
import SuperChat from '@/components/super-chat'
import VipChat from '@/components/vip-chat'
import {ElMessage} from 'element-plus'

const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  config: {
    type: Object,
    default: () => {
    }
  },
  interactive: {
    type: Boolean,
    default: false
  }
})
const translate = inject('translate') // 翻译
const container = ref()
const scrollFlag = ref(true)
const pauseFlag = ref(false)
const currentList = ref([])
provide('config', readonly(props.config))

function handleClick() {
  if (!props.interactive) return
  pauseFlag.value = !pauseFlag.value
  ElMessage[pauseFlag.value ? 'warning' : 'success'](translate(pauseFlag.value ? '弹幕滚动已暂停' : '弹幕滚动已启动'))
}

// 封装一个回到底部或者顶部的函数
function scrollToTop(ele) {
  // 获取当前元素滚动的距离
  let scrollTopDistance = ele.scrollTop
  // 可以滚动的范围
  let pos =  Math.ceil(ele.scrollHeight - ele.clientHeight)
  // 需要滚动的距离（匀速滚动）
  let distance = pos - scrollTopDistance
  // 分段次数
  let times = 0, count = 6

  function smoothScroll() {
    // 需要滚动的距离（缓冲滚动）
    // let distance = pos - scrollTopDistance
    scrollTopDistance = scrollTopDistance + Math.ceil(distance / count)
    ele.scrollTo(0, scrollTopDistance)
    // 判断条件
    // if (Math.abs(distance) <= 1) return scrollFlag.value = true
    if (times++ >= count) return scrollFlag.value = true
    // requestAnimationFrame(smoothScroll)
    setTimeout(smoothScroll, 10)
  }

  smoothScroll()
}

watch(() => props.list, () => {
  if (!scrollFlag.value || pauseFlag.value) return
  scrollFlag.value = false
  currentList.value = props.list
  nextTick(() => scrollToTop(container.value))
}, {deep: true})

let styleElement = document.createElement('style')
styleElement.innerHTML = props.config['style']
document.getElementsByTagName('head')[0].appendChild(styleElement)
watch(() => props.config, () => {
  styleElement.innerHTML = props.config['style']
}, {immediate: true, deep: true})

onActivated(() => container.value?.scrollTo({top: Number.MAX_SAFE_INTEGER}))
</script>

<style lang="scss">
.live-container {
  width: 100%;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.live-container::-webkit-scrollbar {
  width: 0;
  height: 0;
}
</style>